//#define _XOPEN_SOURCE  1
#define _SVID_SOURCE  1
//#define _POSIX_SOURCE  1
//#define _BSD_SOURCE  1
#include <header.h>
#include "/www/server/mysql/include/mysql.h"

void finish_with_error(MYSQL *con) {
    fprintf(stderr, "%s\n", mysql_error(con));
    mysql_close(con);
    exit(1);
}

int main() {
    MYSQL *con = mysql_init(NULL);

    if (con == NULL) {
        fprintf(stderr, "mysql_init() failed\n");
        exit(1);
    }

    // 连接到数据库
    if (mysql_real_connect(con, "localhost", "root", "123456", "testdb1", 0, NULL, 0) == NULL) {
        finish_with_error(con);
    }

    // 预处理SQL语句
    const char *stmt_str = "SELECT id, name, email FROM t_user WHERE id > ?";
    MYSQL_STMT *stmt = mysql_stmt_init(con);
    if (!stmt) {
        finish_with_error(con);
    }

    if (mysql_stmt_prepare(stmt, stmt_str, strlen(stmt_str))) {
        finish_with_error(con);
    }

    // 绑定参数
    int id_threshold = 2; // 示例参数值，可以根据需要更改
    MYSQL_BIND bind[1];
    memset(bind, 0, sizeof(bind));

    bind[0].buffer_type = MYSQL_TYPE_LONG;
    bind[0].buffer = (char *)&id_threshold;
    bind[0].is_null = 0;
    bind[0].length = 0;

    if (mysql_stmt_bind_param(stmt, bind)) {
        finish_with_error(con);
    }

    // 执行查询
    if (mysql_stmt_execute(stmt)) {
        finish_with_error(con);
    }

    // 处理结果集
    MYSQL_BIND result[3];
    memset(result, 0, sizeof(result));

    int id;
    char name[51]; // 修改为 51 字节
    char email[101]; // 100 字节 + 1 字节的NULL终止符
    unsigned long name_len, email_len;

    result[0].buffer_type = MYSQL_TYPE_LONG;
    result[0].buffer = (char *)&id;
    result[0].is_null = 0;
    result[0].length = 0;

    result[1].buffer_type = MYSQL_TYPE_STRING;
    result[1].buffer = name;
    result[1].buffer_length = sizeof(name);
    result[1].is_null = 0;
    result[1].length = &name_len;

    result[2].buffer_type = MYSQL_TYPE_STRING;
    result[2].buffer = email;
    result[2].buffer_length = sizeof(email);
    result[2].is_null = 0;
    result[2].length = &email_len;

    if (mysql_stmt_bind_result(stmt, result)) {
        finish_with_error(con);
    }

    // 从结果集中获取数据
    while (mysql_stmt_fetch(stmt) == 0) {
        name[name_len] = '\0'; // 确保字符串以null结尾
        email[email_len] = '\0'; // 确保字符串以null结尾
        printf("ID: %d, Name: %s, Email: %s\n", id, name, email);
    }

    // 释放资源
    mysql_stmt_close(stmt);
    mysql_close(con);

    return 0;
}